"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 资源池化
Case Name   : 事务中开启子事务
Create At   : 2023.5
Owner       : opentestcase009
Description :
    1、查看集群状态
    2、创建表,插入数据
    3、开启事务并在事务中保存点,进行DML操作后回归保存点
    4、查看数据是否一致
    5、创建存储过程外部SQL回退到存储过程中定义的保存点，并调用
    6、查看数据是否一致
    7、清理环境
Expect      :
    1、集群状态正常,数据库节点状态正常
    2、建表成功,插入数据成功
    3、操作成功
    4、数据与初始一致
    5、创建存储过程成功，调用成功
    6、数据一致
    7、清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SharedStorage(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.comsh = CommonSH('PrimaryDbUser')
        self.t_name = 't_dms_page_017'
        self.pro_name = 'p_dms_page_017'
        self.savepoint = 'savepoint0017'

    def test_shared_storage(self):
        text = '-----step1:查看集群状态; expect:集群状态正常-----'
        self.log.info(text)

        status = self.comsh.exec_cm_ctl(mode='query', param='-Cv')
        self.log.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败' + text)

        text = '-----step2:创建表,插入数据; expect:建表成功,插入数据成功-----'
        self.log.info(text)

        sql = f"create table {self.t_name}(id int,salary int) " \
              f"with(segment=on);" \
              f"insert into {self.t_name} values(generate_series(20,50)," \
              f"generate_series(20,50));" \
              f"select count(*) from {self.t_name};"
        self.log.info(sql)
        res = self.comsh.execut_db_sql(sql)
        self.log.info(res)
        self.assertTrue(self.constant.CREATE_TABLE_SUCCESS in res
                        and self.constant.INSERT_SUCCESS_MSG in res,
                        '执行失败' + text)
        self.assertEqual('31', res.splitlines()[-2].strip(), '执行失败' + text)

        text = '-----step3:开启事务并在事务中保存点,进行DML操作后回归保存点; expect:操作成功-----'
        self.log.info(text)

        trans = f'''start transaction;
                    savepoint {self.savepoint};
                    insert into {self.t_name} values(66,66666);
                    select count(*)from {self.t_name};
                    update {self.t_name} set id = 55 where salary = 44;
                    delete from {self.t_name} where id < 30;
                    select count(*)from {self.t_name};
                    truncate table {self.t_name};
                    select count(*) from {self.t_name};
                    rollback to savepoint {self.savepoint};
                    commit;'''
        self.log.info(trans)

        res_trans = self.comsh.execut_db_sql(trans)
        self.log.info(res_trans)

        self.assertIn('SAVEPOINT', res_trans, '检查点开启失败')
        self.assertIn(self.constant.ROLLBACK_MSG, res_trans,
                      '执行失败' + text)

        text = '-----step4:查看数据是否一致; expect:数据与回滚前一致-----'''
        self.log.info(text)

        sql = f'''select count(*) from {self.t_name};'''
        self.log.info(sql)

        res = self.comsh.execut_db_sql(sql)
        self.log.info(res)
        self.assertEqual('31', res.splitlines()[-2].strip(), '执行失败' + text)

        text = '-----step5:创建存储过程外部SQL回退到存储过程中定义的保存点; expect:创建成功-----'
        self.log.info(text)

        proce = f'''create or replace procedure {self.pro_name}()
                    as
                    begin
                        insert into {self.t_name} values(1);
                        savepoint {self.savepoint};
                        insert into {self.t_name} values(2);
                    end;'''
        self.log.info(proce)

        cre_proce = self.comsh.execut_db_sql(proce)
        self.log.info(cre_proce)
        self.assertIn(self.constant.CREATE_PROCEDURE_SUCCESS_MSG, cre_proce,
                      '执行失败' + text)

        call_sql = f'''begin;
                       insert into {self.t_name} values(3);
                       call {self.pro_name}();
                       rollback to savepoint {self.savepoint};
                       select * from {self.t_name};
                       commit;'''
        self.log.info(call_sql)
        call_pro = self.comsh.execut_db_sql(call_sql)
        self.log.info(call_pro)
        self.assertIn('COMMIT', call_pro, '调用存储过程失败')

        text = '-----step5:查看数据是否一致; expect:数据一致-----'
        self.log.info(text)

        select = f'''select count(*) from {self.t_name};'''
        self.log.info(select)
        select_res = self.comsh.execut_db_sql(select)
        self.log.info(select_res)
        self.assertEqual('33', select_res.splitlines()[-2].strip(),
                         '执行失败' + text)

    def tearDown(self):
        text = '-----step6:清理环境,删除表; expect:清理环境成功-----'
        self.log.info(text)

        clear = f'''drop table {self.t_name} cascade;
            drop procedure {self.pro_name};'''
        self.log.info(clear)
        clear_res = self.comsh.execut_db_sql(clear)
        self.log.info(clear_res)

        self.assertIn(self.constant.DROP_TABLE_SUCCESS, clear_res,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_PROCEDURE_SUCCESS_MSG, clear_res,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
